package org.cuit.lmq.filter;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.cuit.lmq.constants.enums.RedisKeyEnum;
import org.cuit.lmq.domain.security.LoginUser;
import org.cuit.lmq.utils.JwtUtil;
import org.cuit.lmq.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Seon
 * @date 2023/3/4
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    /**
     * 1.获取token
     * 2.解析token中的userId
     * 3.从redis里面拿到用户的信息
     * 4.存入SecurityContextHolder中保存用户状态
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getId();
        } catch (Exception e) {
            log.warn("有用户非法访问");
            throw new RuntimeException("token非法");
        }

        String redisKey = RedisKeyEnum.LOGIN_USER.getValue() + userId;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if (ObjectUtils.isNull(loginUser)) {
            throw new RuntimeException("用户未登录");
        }
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, loginUser.getPassword(), loginUser.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
